#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Ansible Playbook 自动生成器
支持多任务与模板选择
"""

import yaml
import os
from datetime import datetime

TEMPLATES = {
    "install_package": {
        "desc": "安装软件包（使用 yum/apt 模块）",
        "module": "yum",
        "args": {"name": "", "state": "present"}
    },
    "copy_file": {
        "desc": "复制文件到远程主机",
        "module": "copy",
        "args": {"src": "", "dest": ""}
    },
    "run_command": {
        "desc": "执行 Shell 命令",
        "module": "shell",
        "args": {"cmd": ""}
    },
    "restart_service": {
        "desc": "重启指定服务",
        "module": "service",
        "args": {"name": "", "state": "restarted"}
    },
    "create_user": {
        "desc": "创建用户账户",
        "module": "user",
        "args": {"name": "", "state": "present", "shell": "/bin/bash"}
    },
    "manage_service": {
        "desc": "管理系统服务状态",
        "module": "service",
        "args": {"name": "", "state": "started", "enabled": True}
    },
    "download_file": {
        "desc": "从网络下载文件",
        "module": "get_url",
        "args": {"url": "", "dest": "", "mode": "0644"}
    },
    "set_file_permissions": {
        "desc": "设置文件或目录权限",
        "module": "file",
        "args": {"path": "", "owner": "", "group": "", "mode": "", "state": "file"}
    },
    "create_directory": {
        "desc": "创建目录",
        "module": "file",
        "args": {"path": "", "state": "directory", "mode": "0755"}
    },
    "template_file": {
        "desc": "使用模板生成配置文件",
        "module": "template",
        "args": {"src": "", "dest": ""}
    },
    "add_cron_job": {
        "desc": "添加定时任务",
        "module": "cron",
        "args": {"name": "", "minute": "*", "hour": "*", "job": ""}
    },
    "fetch_file": {
        "desc": "从远程主机拉取文件",
        "module": "fetch",
        "args": {"src": "", "dest": "", "flat": True}
    },
    "unarchive_file": {
        "desc": "解压归档文件",
        "module": "unarchive",
        "args": {"src": "", "dest": "", "remote_src": False}
    },
        "replace_in_file": {
        "desc": "在文件中替换内容",
        "module": "replace",
        "args": {
            "path": "",
            "regexp": "",
            "replace": "",
            "backup": True
        }
    },
    "manage_firewall": {
        "desc": "管理防火墙规则",
        "module": "firewalld",
        "args": {"port": "", "permanent": True, "state": "enabled"}
    },
    "execute_script": {
        "desc": "在远程主机上执行脚本",
        "module": "script",
        "args": {
            "cmd": "",
            "creates": "",
            "removes": ""
        }
    },
    "debug_output": {
        "desc": "调试输出变量或消息",
        "module": "debug",
        "args": {
            "msg": "",
            "var": "",
            "verbosity": 0
        }
    }
}


def choose_template():
    """让用户选择模板"""
    print("\n=== 任务模板列表 ===")
    templates_list = list(TEMPLATES.items())
    
    # 显示所有模板选项
    for idx, (key, tpl) in enumerate(templates_list, start=1):
        print(f"{idx}. {tpl['desc']} ({key})")
    
    # 获取用户选择
    while True:
        try:
            choice = input(f"请选择模板编号 (1-{len(templates_list)}): ").strip()
            choice_idx = int(choice) - 1
            
            if 0 <= choice_idx < len(templates_list):
                return templates_list[choice_idx][0]
            else:
                print(f"❌ 请输入有效的数字 (1-{len(templates_list)})")
        except ValueError:
            print("❌ 请输入有效的数字")


def fill_args(template_key):
    """根据模板让用户输入参数"""
    tpl = TEMPLATES[template_key]
    module_args = {}
    print(f"\n配置任务参数（模板：{tpl['desc']}）:")
    
    for k, v in tpl["args"].items():
        # 根据参数类型提供不同的提示
        if isinstance(v, bool):
            default_str = "y" if v else "n"
            user_input = input(f"请输入 {k} (默认: {default_str}): ").strip().lower()
            if user_input in ['y', 'yes', 'true']:
                module_args[k] = True
            elif user_input in ['n', 'no', 'false']:
                module_args[k] = False
            else:
                module_args[k] = v
        elif isinstance(v, int):
            default_str = str(v)
            user_input = input(f"请输入 {k} (默认: {default_str}): ").strip()
            if user_input:
                try:
                    module_args[k] = int(user_input)
                except ValueError:
                    print(f"❌ 输入无效，使用默认值: {v}")
                    module_args[k] = v
            else:
                module_args[k] = v
        else:
            # 处理字符串类型的参数
            default_str = v if v != "" else "(空)"
            user_input = input(f"请输入 {k} (默认: {default_str}): ").strip()
            module_args[k] = user_input if user_input else v
    
    return tpl["module"], module_args


def main():
    print("=== 🧩 自动生成 Ansible Playbook 工具 ===")
    task_name = input("请输入Playbook名称: ") or "Auto Generated Playbook"
    hosts = input("请输入目标主机组（默认 all）: ") or "all"
    become = input("是否使用sudo权限？(y/n): ").lower() == "y"

    tasks = []
    while True:
        tpl_key = choose_template()
        module_name, module_args = fill_args(tpl_key)
        task_title = input("请输入该任务名称: ") or f"{tpl_key} task"

        tasks.append({
            "name": task_title,
            module_name: module_args
        })

        more = input("\n是否继续添加任务？(y/n): ").lower()
        if more != "y":
            break

    playbook = [{
        "name": task_name,
        "hosts": hosts,
        "become": become,
        "tasks": tasks
    }]

    # 保存为文件
    filename = f"playbook_{datetime.now().strftime('%Y%m%d_%H%M%S')}.yml"
    with open(filename, "w", encoding="utf-8") as f:
        yaml.dump(playbook, f, sort_keys=False, allow_unicode=True)

    print(f"\n✅ 已生成Playbook文件: {filename}")




if __name__ == "__main__":
    main()
